<?php

namespace Biz\Services\Notify;

use Biz\Models\App\App;
use Lumen\Logger\Logger;
use Biz\Models\Notify\Notify;
use Illuminate\Support\Facades\DB;
use Lumen\Core\Exceptions\BusinessException;
use Biz\Repositories\Notify\NotifyRepository;

/**
 * NotifyService.
 *
 * @license [http://www.85do.com] [杭州永奥网络科技有限公司]
 * @copyright Copyright (c) 2018-2026 Hangzhou Yongao Technology Co., Ltd. All rights reserved.
 */
class NotifyService
{
    /**
     * @var \Lumen\Repository\Contracts\RepositoryContract
     */
    protected $repository;

    /**
     * RepositoryController constructor.
     *
     * @param NotifyRepository $repository
     */
    public function __construct(NotifyRepository $repository)
    {
        $this->repository         = $repository;
    }

    /**
     * Create.
     *
     * @param array $data
     *
     * @throws \Exception
     *
     * @return Notify
     */
    public function create(array $data): Notify
    {
        // type default
        if (! isset($data['type'])) {
            throw new BusinessException('通知类型不可为空');
        }

        if (! isset($data['gateway'])) {
            throw new BusinessException('支付网关不可为空');
        }

        if (! isset($data['driver'])) {
            throw new BusinessException('支付驱动不可为空');
        }

        // 1) Start Transaction
        DB::beginTransaction();
        try {
            // 创建站点
            /** @var App $app */
            $app = $this->repository->create($data);
            if (! $app) {
                throw new BusinessException('通知创建失败');
            }

            // 2) Commit Transaction
            DB::commit();
        } catch (\Exception $e) {
            // 3) Rollback Transaction
            DB::rollback();
            // 4) Log Transaction
            Logger::error(__CLASS__, __FUNCTION__, $e);
            // 5) Throw Exception
            throw $e;
        }

        return $app;
    }
}
